package com.xci.platform.auth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.map.MapUtil;
import com.xci.platform.auth.entity.LogEntity;
import com.xci.platform.auth.entity.ReleaseHistoryEntity;
import com.xci.platform.auth.entity.UserEntity;
import com.xci.platform.auth.core.LoginModel;
import com.xci.platform.auth.service.OnlineUserService;
import com.xci.platform.auth.service.ReleaseHistoryService;
import com.xci.platform.auth.service.UserService;
import com.xci.platform.core.Constant;
import com.xci.platform.annotation.AllowAnonymous;
import com.xci.platform.annotation.Authorize;
import com.xci.platform.core.BoolMessage;
import com.xci.platform.core.GMap;
import com.xci.platform.helper.CookieHelper;
import com.xci.platform.helper.CoreHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 权限子系统默认控制器
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/")
public class DefaultController extends AuthBaseController {

    /**
     * 系统用户服务
     */
    @Resource
    protected UserService userService;

    /**
     * 系统发布记录服务
     */
    @Resource
    private ReleaseHistoryService releaseHistoryService;

    /**
     * 系统在线用户服务
     */
    @Resource
    protected OnlineUserService onlineUserService;

    //region 页面视图

    @GetMapping("/")
    public String index(ModelMap map) {
        map.put("authUser", currentUser());
        map.put("systemTitle", authHelper.getParamValue("SystemTitle", "西交投信息系统开发平台"));
        map.put("systemTitleColor", authHelper.getParamValue("SystemTitleColor", "white"));
        map.put("systemCopyright", authHelper.getParamValue("SystemCopyright", "西安交通信息投资营运有限公司 版权所有"));
        map.put("systemTitleVersion", authHelper.getParamValue("SystemTitleVersion", "测试版"));
        map.put("systemTitleVersionColor", authHelper.getParamValue("SystemTitleVersionColor", "yellow"));
        return "auth/default/index";
    }

    @GetMapping("/home")
    public String home(ModelMap map) {
        map.put("userOwneRoleString", authHelper.getRoleString(currentUser()));
        return "auth/default/home";
    }

    @AllowAnonymous
    @GetMapping("/login")
    public String login(HttpServletRequest request, ModelMap map) {
        boolean loginResult = authHelper.checkAndAutoLogin(request);
        if (loginResult) {
            return redirect(request.getContextPath() + "/");
        }
        map.put("systemTitle", authHelper.getParamValue("SystemTitle", "西交投信息系统开发平台"));
        map.put("systemTitleColor", authHelper.getParamValue("SystemTitleColor", "white"));
        map.put("systemCopyright", authHelper.getParamValue("SystemCopyright", "西安交通信息投资营运有限公司 版权所有"));
        return "auth/default/login";
    }

    @AllowAnonymous
    @GetMapping("/unauthorized")
    public String unauthorized(String code1, String code2, ModelMap map) {
        map.put("code1", code1);
        map.put("code2", code2);
        return "error/default/unauthorized";
    }

    /**
     * 验证码
     */
    @AllowAnonymous
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captcha);

        // 禁止缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setContentType("image/jpeg");

        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        outputStream.close();
    }


    @AllowAnonymous
    @GetMapping("/about")
    public String about(ModelMap map) {
        List<ReleaseHistoryEntity> list = releaseHistoryService.query(GMap.newMap("hasContent", "1"));
        map.put("releaseHistoryList", list);
        return "auth/default/about";
    }

    //endregion

    //region 公共视图

    /**
     * 图标页面
     */
    @AllowAnonymous
    @GetMapping("/icon")
    public String icon() {
        return "_common/icon";
    }

    //endregion

    //region 数据处理

    @AllowAnonymous
    @ResponseBody
    @PostMapping("/login")
    public BoolMessage login(@ModelAttribute LoginModel model, HttpServletRequest request) throws UnsupportedEncodingException {
        long startTime = CoreHelper.startWatch();
        BoolMessage<UserEntity> result = userService.login(model.getAccount(), model.getPassword());
        if (result.isSuccess()) {
            UserEntity entity = result.getData();
            BoolMessage sresult = authHelper.onLoginSuccess(entity, startTime, request);
            if (!sresult.isSuccess()) {
                return sresult;
            }
            if (model.isAutoLogin()) {
                authHelper.setUserCookie(entity);
            }
            return new BoolMessage<>(true, GMap.newMap("url", request.getContextPath() + "/"));
        }
        return result;
    }

    /**
     * 检查验证码
     *
     * @param uuid    户端唯一ID
     * @param captcha 用户输入的验证码
     * @return 输入验证码正确返回True
     */
    private boolean checkCaptcha(String uuid, String captcha) {
        return true;
    }

    /**
     * 检查账号锁定状态
     */
    @AllowAnonymous
    @ResponseBody
    @PostMapping("/checkLock")
    public BoolMessage checkLock(String account) {
        return BoolMessage.False;
    }

    @ResponseBody
    @PostMapping("/logout")
    public BoolMessage logout(HttpServletRequest request, HttpSession session) {
        long startTime = CoreHelper.startWatch();
        //注销在线用户
        onlineUserService.logoff(currentUser().getUserId());

        session.removeAttribute(Constant.UserSessionKey);
        CookieHelper.removeCookie(Constant.UserCookieKey);

        //添加登录审计日志
        LogEntity logEntity = authHelper.buildAuditInfo(request, "退出系统", CoreHelper.stopWatch(startTime));
        logService.insert(logEntity);
        return new BoolMessage<>(true, MapUtil.of("url", request.getContextPath() + "/login"));
    }

    //endregion
}
